package com.github.xzb617.client.base.lb;

import com.github.xzb617.client.base.props.ClientProperties;
import com.github.xzb617.client.base.utils.ServerUtil;
import com.github.xzb617.rpc.LoadBalanceCaller;
import com.github.xzb617.rpc.core.RequestCaller;
import com.github.xzb617.rpc.entity.RpcConfig;
import com.github.xzb617.rpc.entity.Server;
import com.github.xzb617.rpc.httpclient.HttpClientRequestCaller;
import com.github.xzb617.rpc.loadbalancer.LoadBalancer;
import com.github.xzb617.rpc.loadbalancer.factory.LbBeanCreatedException;
import com.github.xzb617.rpc.loadbalancer.factory.LbBeanFactory;

import java.util.List;

/**
 * 服务端负载均衡器工厂
 * <p>
 *     1.生成客户端向服务端请求的负载均衡请求 LoadBalanceCaller
 *     2.依赖ClientProperties
 * </p>
 * @author xzb617
 */
public class ServerLoadBalanceFactory {

    public static LoadBalanceCaller createLoadBalanceRpcBroker(ClientProperties clientProperties) throws LbBeanCreatedException {
        List<Server> servers = generateServers(clientProperties);
        RequestCaller rpcSender = createRpcCaller(clientProperties);
        LoadBalancer loadBalancer = createLoadBalancer(clientProperties);
        return new LoadBalanceCaller(servers, rpcSender, loadBalancer);
    }

    private static RequestCaller createRpcCaller(ClientProperties clientProperties) {
        // 初始化 RpcSender
        RpcConfig rpcConfig = new RpcConfig();
        rpcConfig.setEncode("UTF-8");
        rpcConfig.setTimeout(70000);
        RequestCaller requestCaller = new HttpClientRequestCaller(rpcConfig);
        return requestCaller;
    }

    private static LoadBalancer createLoadBalancer(ClientProperties clientProperties) throws LbBeanCreatedException {
        return LbBeanFactory.getInstance(clientProperties.getLoadBalanceStrategy());
    }

    private static List<Server> generateServers(ClientProperties clientProperties) {
        String serverAddr = clientProperties.getServerAddrs();
        return ServerUtil.parseServers(serverAddr);
    }

}
